
# -*- coding: utf-8 -*-
#   基础TableView类
# @Time    ： 2021/12/1  23:09
# @Auther  ： 徐良
# File     :  baseTableView.py
from PySide6 import QtWidgets
from PySide6.QtWidgets import QTableView
from PySide6.QtCore import Qt


class BaseTableView(QTableView):
    """
    基础TableView类
    """
    def __init__(self, parent=None):
        super(BaseTableView, self).__init__(parent)
        # tableView 回车事件
        self.keyPressEvent = self.tableKeyPressEvent

    # 设置tableView的表格标题
    def setHeader(self, iList):
        """
        设置表格标题
        :param iList:
        """
        i = 0
        for fn in iList:
            self.model().setHeaderData(i, Qt.Horizontal, fn)
            i = i + 1

    def setHideColumnForCol(self, ilist):
        """
        设置影藏列
        :param ilist:
        :return:
        """
        ii = 0
        for obj in ilist:
            self.setColumnHidden(ii, not obj)
            ii += 1

    def setHideColumnForPosition(self, sList):
        """
        按指定位置设置影藏列
        :param sList:
        :return:
        """
        for pos in sList:
            self.setColumnHidden(int(pos), 1)


    def setColumnWidthForList(self, ilist):
        """
        设置列宽
        :param ilist:
        :return:
        """
        i = 0
        for w in ilist:
            if w != '':
                self.setColumnWidth(i, int(w))
            i += 1

    def tableKeyPressEvent(self, event):
        """
        按回车后的事件
        :param event:
        :return:
        """
        QtWidgets.QTableView.keyPressEvent(self, event)  # 返回事件调度权

        if event.key() in (Qt.Key_Return, Qt.Key_Enter):
            current = self.currentIndex()
            nextIndex = current.sibling(current.row(), current.column() + 1)
            if nextIndex.isValid():
                self.activateWindow()
                self.setFocus()
                self.setCurrentIndex(nextIndex)
                self.edit(nextIndex)

            else:
                nextIndex = current.sibling(current.row() + 1, 0)
                if nextIndex.isValid():
                    self.activateWindow()
                    self.setFocus()
                    self.setCurrentIndex(nextIndex)
                    self.edit(nextIndex)
